﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

using Commons.Collections;

using Spring.Core.IO;

using NVelocity.Runtime.Resource.Loader;

using Yawf.Core.Utils;
using Yawf.Web.Managers.Entities;

namespace Yawf.Web.Managers {
	public class MVCResourceLoader : ResourceLoader{
		private Encoding outputEncoding = Encoding.UTF8;

		public Encoding OutputEncoding { get { return outputEncoding; } set { outputEncoding = value; } }
	
		/// <summary>
		/// Inits the resource loader
		/// </summary>
		/// <param name="configuration">Configuration parameters</param>
		public override void Init(ExtendedProperties configuration){
			// Do nothing
		}

		public override System.IO.Stream GetResourceStream(String source) {
			FileInfo fileInfo;
			View view;

			// Need to check this cause NVelocity asks for this file
			// When Spring initializes and that should not be done cause 
			// ResourceUtils.GetFileResource calls Initializer and that cant be done 
			// While initializing spring
			if (source == "VM_global_library.vm") {
				// Open the same file in the root of the application
				String path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"\VM_global_library.vm";
				if (File.Exists(path)) {
					return new FileStream(path, FileMode.Open);
				}
			} else {
				fileInfo = ResourceUtils.GetFileResource(source);
				if (fileInfo != null && fileInfo.Extension != null && fileInfo.Extension.ToUpper() == ".XML") {
					view = new View(source);
					return new MemoryStream(OutputEncoding.GetBytes(view.Content));
				}
				return new FileStream(fileInfo.FullName, FileMode.Open);
			}

			return null;
		}

		// by now caching is not supported, so always true.
		public override bool IsSourceModified(NVelocity.Runtime.Resource.Resource resource) {
			return true;
		}

		public override long GetLastModified(NVelocity.Runtime.Resource.Resource resource) {
			// Need to check this cause NVelocity asks for this file
			// When Spring initializes and that should not be done cause 
			// ResourceUtils.GetFileResource calls Initializer and that cant be done 
			// While initializing spring
			if (resource.Name == "VM_global_library.vm") {
				String path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"\VM_global_library.vm";
				return File.GetLastWriteTime(path).Ticks;
			} else {
				return ResourceUtils.GetFileResource(resource.Name).LastWriteTime.Ticks;
			}
		}
	}
}
